<template>
  <ve-card title="订单排车" :customContentStyle="{ paddingBottom: 0 }" v-bind="$attrs">
    <template #forever-show="{ contentIsShow }">
      <ve-form-item label="车辆来源" class="car-origin" required>
        <ve-radio v-model="form.carSource" :list="dict.carSourceEnum" @confirm="changeCarSourceFn" />
      </ve-form-item>
      <!-- 创建订单 -->
      <ve-form-item
        v-if="mode == 'default'"
        label="车牌号"
        :required="isTiexing"
        prop="carLicenseNo"
        labelTooltipContent="请先选择租赁周期和取车门店后，再选择排车车辆"
        :borderBottom="contentIsShow"
      >
        <CustomSelect tip="请先选择租赁周期和取车门店后，再选择排车车辆" @click="customSelectTap" :modelValue="form.carLicenseNo" />
      </ve-form-item>
      <!-- 换车 -->
      <ve-form-item prop="carLicenseNo" required v-if="mode == 'changeCar'" label="车牌号" :borderBottom="contentIsShow">
        <CustomSelect :mode="mode" @click="customSelectTap" :modelValue="form.carLicenseNo" />
      </ve-form-item>
    </template>
    <ve-form-item label="排车车型" labelPosition="top" :borderBottom="mode == 'changeCar' ? true : false">
      <view class="platoon-model">{{ form.carModelName || '-' }}</view>
    </ve-form-item>
  </ve-card>
</template>
<script setup>
  import { ref, inject, computed, watch } from 'vue'
  import { getCarModelStock } from '@/api/asset/car-stock'
  import CustomSelect from '../../components/custom-select.vue'
  const form = inject('form')
  const dict = inject('dict')
  import { onLoad, onUnload } from '@dcloudio/uni-app'
  import dayjs from 'dayjs'
  const props = defineProps({
    mode: {
      type: String,
      default: 'default', // default | changeCar
    },
    oldCarId: Number, // 换车操作时的原车辆id
    isTiexing: {
      type: Boolean,
      default: false,
    },
  })

  // 更换车辆来源
  const changeCarSourceFn = () => {
    form.value.carId = undefined
    form.value.carLicenseNo = undefined
    form.value.carModelId = undefined
    form.value.carModelName = undefined
  }
  const _param = (obj) => {
    let str = ''
    if (typeof obj == 'object') {
      for (let i in obj) {
        if (obj[i] == undefined) {
          continue
        }
        str += i + '=' + obj[i] + '&'
      }
    }
    return str.replace(/&$/g, '')
  }
  const orderSourceName = computed(() => {
    let list = dict.orderSourceEnum
    let findResult = list?.find((item) => item.value == form.value.orderSource)
    return findResult ? findResult.label : '-'
  })

  // 点击车牌选择事件
  const customSelectTap = () => {
    // 跳转选择车牌号页面
    let orderInfo = {
      // 当前选中的车辆 id
      carId: form.value.carId,
      siteId: form.value.siteId,
      siteName: form.value.siteName,
      modelId: form.value.originalModelId,
      modelName: form.value.originalModelName,
      startTime: form.value.startTime,
      endTime: form.value.endTime,
      rentDays: form.value.rentDays,
      carSource: form.value.carSource,
      // 订单来源
      orderSourceName: form.value.orderSourceName || orderSourceName.value,
    }
    if (props.mode == 'changeCar') {
      // 当前选中的车辆 id
      orderInfo.platoonCarId = props.oldCarId
      // 默认将换车时间作为开始时间，并同预计还车时间做比较
      // 1 若早于预计还车时间，则正常处理
      // 2 若晚于预计还车时间，则将实际开始时间设置为开始时间
      let startTime = form.value.replaceTime
      let endTime = form.value.endTime
      if (dayjs(startTime).valueOf() > dayjs(endTime).valueOf()) {
        // 将开始时间设置为预计开始时间
        startTime = orderInfo.startTime
      }
      orderInfo.startTime = startTime
    }
    // 无车辆不缓存筛选条件
    if (!form.value.carId) {
      platoonModelQueryParam.value = {}
    }
    let paramStr = _param({
      mode: 'select',
      type: 'short-order',
      data_json: JSON.stringify({
        ...orderInfo,
        ...platoonModelQueryParam.value,
      }),
      orderInfo_json: JSON.stringify(orderInfo),
    })
    uni.navigateTo({
      url: `/pages/asset/stock/car-stock/selector?${paramStr}`,
    })
  }

  // 选择车牌完成后，函数暴露到上级
  const platoonModelQueryParam = ref({})
  onLoad(() => {
    // 车型选择完成
    uni.$on('carStock:selectCarOk', (carId, option, queryParam) => {
      form.value.carId = carId
      form.value.carLicenseNo = option.licenseNo
      form.value.carModelId = option.modelId
      form.value.carModelName = option.modelName

      // 记录弹窗queryParam
      platoonModelQueryParam.value = { ...queryParam }

      // 更新下单车型
      getCarModelStock({
        siteId: form.value.siteId,
        startTime: form.value.startTime,
        endTime: form.value.endTime,
      }).then((res) => {
        const result = res.result
        if (result && result.list) {
          // 车型列表
          const lists = result.list
          // 是否有同名车型
          const carModelId = option.modelId
          const sameModel = lists.find((item) => item.id === carModelId)
          // 存在同名车型
          if (sameModel) {
            form.value.originalModelId = sameModel.id
            form.value.originalModelName = sameModel.modelName
          } else {
            form.value.originalModelId = undefined
            form.value.originalModelName = undefined
          }
        } else {
          // 不存在车型
          form.value.originalModelId = undefined
          form.value.originalModelName = undefined
        }
      })
    })
  })
  onUnload(() => {
    uni.$off('carStock:selectCarOk')
  })
</script>
<style lang="less" scoped>
  .platoon-model {
    width: 100%;
    background: #f7f8fa;
    padding: 34rpx 24rpx;
    font-size: 30rpx;
    color: #191c27;
  }
  .car-origin {
    /deep/ .ve-form-item__body {
      align-items: center;
    }
  }
</style>
